<template>
  <div class="diary-create-container">
    <!-- 顶部导航栏 -->
    <header class="top-nav">
      <button class="back-button" @click="goBack">返回</button>
      <h1 class="page-title">记录我的情绪</h1>
      <div class="nav-right"></div>
    </header>

    <!-- 核心内容区 -->
    <main class="content-wrapper">
      <div class="core-content">
        <!-- 情绪标签选择区 -->
        <section class="emotion-tags-section">
          <div class="tags-container">
            <button
              v-for="tag in emotionTags"
              :key="tag.value"
              :class="['emotion-tag', { selected: selectedEmotion === tag.value }]"
              :style="getTagStyle(tag)"
              @click="selectEmotion(tag.value)"
            >
              {{ tag.label }}
            </button>
          </div>
        </section>

        <!-- 心情评分区 -->
        <section class="mood-score-section">
          <div class="score-wrapper">
            <span class="score-label">今日心情分：</span>
            <div class="slider-container">
              <input
                type="range"
                class="mood-slider"
                min="1"
                max="10"
                v-model.number="moodScore"
                @input="updateMoodScore"
              />
              <span class="score-value">{{ moodScore }}</span>
            </div>
          </div>
        </section>

        <!-- 日记内容区 -->
        <section class="diary-content-section">
          <div class="editor-container">
            <div
              class="rich-text-editor"
              contenteditable="true"
              v-html="editorContent"
              @input="updateEditorContent"
              @paste="handlePaste"
              :placeholder="placeholderText"
            ></div>
            <div class="editor-toolbar">
              <button class="toolbar-btn" @click="formatText('bold')" title="加粗">
                <strong>B</strong>
              </button>
              <button class="toolbar-btn" @click="formatText('italic')" title="斜体">
                <em>I</em>
              </button>
              <div class="emoji-dropdown">
                <button class="toolbar-btn" @click="toggleEmojiPicker" title="表情">😊</button>
                <div v-if="showEmojiPicker" class="emoji-picker">
                  <span
                    v-for="emoji in emojis"
                    :key="emoji"
                    class="emoji-item"
                    @click="insertEmoji(emoji)"
                  >
                    {{ emoji }}
                  </span>
                </div>
              </div>
            </div>
            <div class="word-count" :class="{ 'limit-reached': wordCount >= 1000 }">
              {{ wordCount }}字
            </div>
          </div>
        </section>
      </div>
    </main>

    <!-- 底部操作区 -->
    <footer class="bottom-actions">
      <div class="buttons-container">
        <button class="save-draft-btn" @click="saveDraft">保存草稿</button>
        <button
          class="submit-diary-btn"
          :disabled="!canSubmit"
          @click="submitDiary"
        >
          提交日记
        </button>
      </div>
    </footer>

    <!-- 提示框 -->
    <transition name="fade">
      <div v-if="showToast" class="toast-notification">
        {{ toastMessage }}
      </div>
    </transition>
  </div>
</template>

<script>
export default {
  name: 'DiaryCreateView',
  data() {
    return {
      selectedEmotion: '',
      moodScore: 5,
      editorContent: '',
      showEmojiPicker: false,
      showToast: false,
      toastMessage: '',
      placeholderText: '在这里写下你的心情吧～ 可以说说今天发生的事、你的感受...',
      emotionTags: [
        { label: '开心', value: 'happy', color: '#E0B5B5' },
        { label: '焦虑', value: 'anxious', color: '#94A7C8' },
        { label: '悲伤', value: 'sad', color: '#E8E8E8' },
        { label: '平静', value: 'calm', color: '#B4C7DC' },
        { label: '愤怒', value: 'angry', color: '#F2D4B7' },
        { label: '迷茫', value: 'confused', color: '#F5F5F5' }
      ],
      emojis: ['😊', '🌟', '🌸', '💖', '✨', '🌈', '🌺', '🌼', '💫', '💕']
    }
  },
  computed: {
    canSubmit() {
      return this.selectedEmotion && this.stripHtml(this.editorContent).trim() !== ''
    },
    wordCount() {
      return this.stripHtml(this.editorContent).length
    }
  },
  mounted() {
    this.loadDraft()
    // 点击外部关闭表情选择器
    document.addEventListener('click', this.handleClickOutside)
  },
  beforeUnmount() {
    document.removeEventListener('click', this.handleClickOutside)
  },
  methods: {
    selectEmotion(emotion) {
      this.selectedEmotion = emotion
    },
    getTagStyle(tag) {
      const isSelected = this.selectedEmotion === tag.value
      return {
        backgroundColor: isSelected ? tag.color : '#F0F0F0',
        color: isSelected ? '#FFFFFF' : '#666666'
      }
    },
    updateMoodScore(event) {
      this.moodScore = parseInt(event.target.value)
    },
    updateEditorContent(event) {
      const content = event.target.innerHTML
      const textLength = this.stripHtml(content).length
      
      // 限制字数
      if (textLength >= 1000) {
        const truncatedText = this.stripHtml(content).substring(0, 1000)
        event.target.innerHTML = truncatedText
      } else {
        this.editorContent = content
      }
    },
    handlePaste(event) {
      event.preventDefault()
      const text = event.clipboardData.getData('text/plain')
      document.execCommand('insertText', false, text)
    },
    formatText(command) {
      document.execCommand(command, false, null)
      this.$refs.editor.focus()
    },
    toggleEmojiPicker(event) {
      event.stopPropagation()
      this.showEmojiPicker = !this.showEmojiPicker
    },
    insertEmoji(emoji) {
      document.execCommand('insertText', false, emoji)
      this.showEmojiPicker = false
    },
    handleClickOutside(event) {
      if (!event.target.closest('.emoji-dropdown')) {
        this.showEmojiPicker = false
      }
    },
    stripHtml(html) {
      const tempDiv = document.createElement('div')
      tempDiv.innerHTML = html
      return tempDiv.textContent || tempDiv.innerText || ''
    },
    saveDraft() {
      const draft = {
        emotion: this.selectedEmotion,
        moodScore: this.moodScore,
        content: this.editorContent
      }
      localStorage.setItem('diaryDraft', JSON.stringify(draft))
      this.showToastMessage('草稿已保存～')
    },
    loadDraft() {
      const draft = localStorage.getItem('diaryDraft')
      if (draft) {
        try {
          const parsedDraft = JSON.parse(draft)
          this.selectedEmotion = parsedDraft.emotion || ''
          this.moodScore = parsedDraft.moodScore || 5
          this.editorContent = parsedDraft.content || ''
        } catch (e) {
          console.error('加载草稿失败', e)
        }
      }
    },
    submitDiary() {
      if (!this.canSubmit) return
      
      // 这里可以添加API调用逻辑
      console.log('提交日记', {
        emotion: this.selectedEmotion,
        moodScore: this.moodScore,
        content: this.editorContent
      })
      
      // 清除草稿
      localStorage.removeItem('diaryDraft')
      
      // 显示成功提示
      this.showToastMessage('情绪记录成功！')
      
      // 2秒后跳转
      setTimeout(() => {
        this.goBack()
      }, 2000)
    },
    showToastMessage(message) {
      this.toastMessage = message
      this.showToast = true
      setTimeout(() => {
        this.showToast = false
      }, 3000)
    },
    goBack() {
      this.$router.push('/diary')
    }
  }
}
</script>

<style scoped>
.diary-create-container {
  min-height: 100vh;
  background-color: #F9F9F9;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

/* 顶部导航栏 */
.top-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  background-color: #FFFFFF;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-button {
  padding: 8px 16px;
  background-color: transparent;
  border: none;
  color: #666666;
  font-size: 16px;
  cursor: pointer;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.back-button:hover {
  background-color: #F0F0F0;
  transform: scale(1.03);
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #333333;
  margin: 0;
}

.nav-right {
  width: 80px;
}

/* 核心内容区 */
.content-wrapper {
  padding: 32px 0;
  display: flex;
  justify-content: center;
}

.core-content {
  width: 100%;
  max-width: 840px;
  padding: 0 24px;
}

/* 情绪标签选择区 */
.emotion-tags-section {
  margin-bottom: 32px;
}

.tags-container {
  display: flex;
  gap: 12px;
  overflow-x: auto;
  padding-bottom: 8px;
  -webkit-overflow-scrolling: touch;
  scrollbar-width: none;
}

.tags-container::-webkit-scrollbar {
  display: none;
}

.emotion-tag {
  padding: 10px 20px;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
  flex-shrink: 0;
}

.emotion-tag:hover {
  transform: scale(1.03);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.emotion-tag.selected {
  font-weight: 500;
}

/* 心情评分区 */
.mood-score-section {
  margin-bottom: 32px;
}

.score-wrapper {
  display: flex;
  align-items: center;
  gap: 20px;
}

.score-label {
  font-size: 16px;
  color: #94A7C8;
  white-space: nowrap;
}

.slider-container {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 16px;
}

.mood-slider {
  flex: 1;
  height: 6px;
  -webkit-appearance: none;
  appearance: none;
  background: #E0E0E0;
  border-radius: 3px;
  outline: none;
  transition: all 0.3s ease;
}

.mood-slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: #94A7C8;
  cursor: pointer;
  transition: all 0.3s ease;
}

.mood-slider::-moz-range-thumb {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: #94A7C8;
  cursor: pointer;
  border: none;
  transition: all 0.3s ease;
}

.mood-slider:hover {
  background: #D0D0D0;
}

.mood-slider:hover::-webkit-slider-thumb {
  background: #7A90B5;
  transform: scale(1.1);
}

.mood-slider:hover::-moz-range-thumb {
  background: #7A90B5;
  transform: scale(1.1);
}

.score-value {
  font-size: 18px;
  font-weight: bold;
  color: #666666;
  min-width: 24px;
  text-align: center;
}

/* 日记内容区 */
.diary-content-section {
  margin-bottom: 40px;
}

.editor-container {
  position: relative;
  background-color: #FFFFFF;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.rich-text-editor {
  min-height: 300px;
  padding: 16px;
  outline: none;
  line-height: 1.6;
  color: #333333;
  font-size: 16px;
}

.rich-text-editor[contenteditable="true"]:empty:before {
  content: attr(placeholder);
  color: #AAAAAA;
  pointer-events: none;
}

.editor-toolbar {
  display: flex;
  gap: 8px;
  padding: 12px 16px;
  background-color: #F8F8F8;
  border-top: 1px solid #EEEEEE;
}

.toolbar-btn {
  width: 36px;
  height: 36px;
  border: none;
  border-radius: 8px;
  background-color: #FFFFFF;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  font-size: 16px;
}

.toolbar-btn:hover {
  background-color: #F0F0F0;
  transform: scale(1.03);
}

.emoji-dropdown {
  position: relative;
}

.emoji-picker {
  position: absolute;
  bottom: 100%;
  left: 0;
  background-color: #FFFFFF;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  padding: 12px;
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 8px;
  margin-bottom: 8px;
  z-index: 10;
}

.emoji-item {
  font-size: 20px;
  cursor: pointer;
  padding: 8px;
  border-radius: 4px;
  text-align: center;
  transition: all 0.2s ease;
}

.emoji-item:hover {
  background-color: #F0F0F0;
}

.word-count {
  position: absolute;
  bottom: 16px;
  right: 16px;
  font-size: 14px;
  color: #999999;
}

.word-count.limit-reached {
  color: #FFA0A0;
}

/* 底部操作区 */
.bottom-actions {
  padding: 24px;
  background-color: #FFFFFF;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
  position: sticky;
  bottom: 0;
}

.buttons-container {
  display: flex;
  justify-content: center;
  gap: 20px;
  max-width: 840px;
  margin: 0 auto;
}

.save-draft-btn,
.submit-diary-btn {
  width: 120px;
  height: 40px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.save-draft-btn {
  background-color: #F0F0F0;
  color: #666666;
}

.save-draft-btn:hover {
  background-color: #E0E0E0;
  transform: scale(1.03);
}

.submit-diary-btn {
  background-color: #94A7C8;
  color: #FFFFFF;
}

.submit-diary-btn:hover:not(:disabled) {
  background-color: #7A90B5;
  transform: scale(1.03);
}

.submit-diary-btn:disabled {
  background-color: #CCCCCC;
  cursor: not-allowed;
  transform: none;
}

/* 提示框 */
.toast-notification {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.6);
  color: #FFFFFF;
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 16px;
  z-index: 1000;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .core-content {
    width: 80%;
  }
}

@media (max-width: 768px) {
  .core-content {
    width: 90%;
    padding: 0 16px;
  }
  
  .content-wrapper {
    padding: 24px 0;
  }
  
  .score-wrapper {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .score-label {
    text-align: center;
  }
  
  .top-nav {
    padding: 12px 16px;
  }
  
  .page-title {
    font-size: 16px;
  }
  
  .buttons-container {
    gap: 16px;
  }
  
  .save-draft-btn,
  .submit-diary-btn {
    width: 100px;
    font-size: 14px;
  }
}
</style>